// src/stores/announcement.ts
import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

// 公告数据接口
export interface Announcement {
  id: number;
  title: string;
  content: string;
  createTime: string;
}

// 公告表单字段配置
export const announcementFields = [
  { key: 'title', label: '标题', type: 'text', placeholder: '请输入公告标题', maxLength: 100, },
  { key: 'content', label: '内容', type: 'textarea', placeholder: '请输入公告内容', maxLength: 1000, },
];

export const useAnnouncementStore = defineStore('announcement', {
  state: () => ({
    announcements: [] as Announcement[],
  }),
  actions: {
    // 获取公告列表（无分页）
    async fetchAnnouncements() {
      try {
        const response = await axios.get('/announcements');
        if (response.data.code === 200) {
          this.announcements = response.data.data; // 直接赋值，类型已匹配
          return this.announcements;
        }
        throw new Error(response.data.message || '获取公告失败');
      } catch (error) {
        throw new Error('获取公告失败');
      }
    },
    // 创建公告
    async createAnnouncement(data: { title: string; content: string }) {
      const response = await axios.post('/announcements', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '创建公告失败');
    },
    // 更新公告
    async updateAnnouncement(data: Announcement) {
      const response = await axios.put('/announcements', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '更新公告失败');
    },
    // 删除公告
    async deleteAnnouncement(id: number) {
      const response = await axios.delete(`/announcements/${id}`);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '删除公告失败');
    },
  },
});
